package com.zmj.service;


import com.zmj.entity.SignUp;
import com.zmj.entity.User;
import com.zmj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param user 表单传过来的User实体
     * @return
     */

    public User login(User user) {
        //先通过mapper层的getUserByAccount查找有没有对应的账号
        User loginUser = userMapper.getUserByAccount(user.getAccount());
        //数据库使用了MD5加密，所以这里验证的时候得把原密码加密一次
        String newPwd = DigestUtils.md5DigestAsHex((user.getPassword() + "mlkh21256257282931").getBytes());
        //如果Dao返回的对象不为空 并且 查询到的密码和加密后的密码一样，说明账号密码验证成功，然后返回相应的User实体
        if (loginUser != null && loginUser.getPassword().equals(newPwd)) {
            // 发放登录成功的token
            String token = UUID.randomUUID().toString();
            userMapper.setTokenToUser(token, loginUser.getId());
            loginUser.setToken(token);
            return loginUser;
        }else {
            //如果Dao返回的对象是空的，或者密码校验补上，就返回null，登录失败
            return null;
        }
    }
/**
 * 用户注册
 * @param user 表单传来的数据
 * @return
 */
public User register(User user){
    //先根据账号查找有没有重复的账号，如果有重复的账号就不给注册，返回null
    if (userMapper.getUserByAccount(user.getAccount())!= null){
        return null;
    }
    //注册之前先把表单传过来的密码根据MD5加密
    String newPwd= DigestUtils.md5DigestAsHex((user.getPassword()+ "mlkh21256257282931").getBytes());
    //加密后在重新注入到user实体里
    user.setPassword(newPwd);
    //根据dao层的register方法判断是否操作成功
    boolean isSuccess = userMapper.register(user)>0;
    System.out.println("插入一条数据，ID是："+ user.getId());
    if (isSuccess){
        //如果成功就返回对象
        return user;
    }else {



        //失败就返回null
        return null;
    }
}

public User getUserByToken(HttpServletRequest request){
    String token = request.getHeader("TOKEN");
    if (token== null){
        return null;
    }
    return userMapper.getUserByToken(token);
}

    public List<User> getUserInfo(){
        List<User> list = userMapper.getUserEn();
        if (list!= null){
            return list;
        }else {
            return null;
        }
    }




}
